package com.bbcare.nutritious.plat.controller;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bbcare.comm.AppException;
import com.bbcare.comm.Constants;
import com.bbcare.comm.DateTimeUtil;
import com.bbcare.comm.ErrorCode;
import com.bbcare.comm.JsonToEnetityUtil;
import com.bbcare.comm.ResultModel;
import com.bbcare.nutritious.plat.entity.PtBloodsugarRecord;
import com.bbcare.nutritious.plat.service.INewBloodSugarService;
/**
 * 
 * @name:         NewBloodSugarController.java
 * @author:       
 * @createTime:   2018年6月1日
 * @description:  血糖控制器
 * @modify:
 *
 */
@Controller
@RequestMapping("/webapi/service/newnutrition")
public class NewBloodSugarController {
	
    public static final Logger logger = Logger.getLogger(NewBloodSugarController.class);
    
    @Autowired
    private INewBloodSugarService newBloodSugarService;

    /**
     * 修改或保存数据
     * @param request
     * @param jsonStr
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/booldSugarJoin")
    public ResultModel<Object> booldSugarJoin(HttpServletRequest request, @RequestBody String jsonStr)throws Exception {
        logger.info("in booldSugarJoin----arg==" + jsonStr);
        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }
        //获取实体参数
        PtBloodsugarRecord bloodsugarRecord = (PtBloodsugarRecord) JsonToEnetityUtil.jsonToObject(requestParam, PtBloodsugarRecord.class);
        //判空
        if(StringUtils.isEmpty(bloodsugarRecord.getUserId())){
        	logger.debug("out UserId----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"患者ID不能为空");
        }
        if(bloodsugarRecord.getSugarValue()==0.0){
        	logger.debug("out SugarValue----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"血糖值不能为空");
        }
        if(StringUtils.isEmpty(bloodsugarRecord.getTestTime())){
        	logger.debug("out TestTime----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"时间不能为空");
        }
        Map<String,Object> rspMap = newBloodSugarService.addOrUpdateById(bloodsugarRecord);
        logger.debug("out booldSugarJoin----arg=="+JSON.toJSONString(rspMap));
        return new ResultModel<Object>(rspMap);
    }
    /**
     * 通过id删除血糖数据
     * @param request
     * @param id
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value="/delBloodsugarRecordById")
    public ResultModel<Object> delBloodsugarRecordById(HttpServletRequest request, String id) throws Exception {
        logger.info("in delBloodsugarRecordById");
        Map<String,Object> rspMap = Collections.synchronizedMap(new HashMap<String,Object>());
        //日期查询条件判断
        if(StringUtils.isEmpty(id)){
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参错误,参数id不能为空");
        }
        rspMap = newBloodSugarService.delBloodsugarRecordById(id);
        logger.debug("out delBloodsugarRecordById----arg=="+JSON.toJSONString(rspMap));
        return new ResultModel<Object>(rspMap);
    }
    /**
     * 分页查询孕妇血糖
     * @param request
     * @param jsonStr
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/listbloodsugarForPage")
    public Map<String, Object> listbloodsugarForPage(HttpServletRequest request, @RequestBody String jsonStr) throws Exception {
        logger.info("in listbloodsugarForPage----arg==" + jsonStr);
        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }
        String flag = requestParam.getString("flag");
        //获取实体参数
        PtBloodsugarRecord bloodsugarRecord = (PtBloodsugarRecord) JsonToEnetityUtil.jsonToObject(requestParam, PtBloodsugarRecord.class);
        //判空
        if(StringUtils.isEmpty(bloodsugarRecord.getUserId())){
        	logger.debug("out UserId----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"患者ID不能为空");
        }
        /*if(bloodsugarRecord.getCurPage()<1){
        	logger.debug("分页页码小于1");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"分页页码不能小于1");
        }*/
        // 针对Datatable特殊处理
        String jsonStrtable = requestParam.getString(Constants.INF_INPUTPARAM_DATATABLE_FIELD);
        int draw = 0;
        if (!StringUtils.isEmpty(jsonStrtable)) {
            JSONObject jsonTable = (JSONObject) JSONObject.parse(jsonStrtable);
            draw = jsonTable.getIntValue("draw");
            bloodsugarRecord.setStartNum(jsonTable.getIntValue("start"));
            bloodsugarRecord.setPageSize(jsonTable.getIntValue("length"));
        }
        //日期查询条件判断
        if(!StringUtils.isEmpty(bloodsugarRecord.getStartDate())){
        	if(StringUtils.isEmpty(bloodsugarRecord.getEndDate())){
        		logger.debug("查询孕妇血糖日期参数单个为空");
            	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参错误,单个日期参数无法查询");
        	}else if(!bloodsugarRecord.getStartDate().equals(bloodsugarRecord.getEndDate()) && DateTimeUtil.compareDate(bloodsugarRecord.getStartDate(),bloodsugarRecord.getEndDate(), DateTimeUtil.yyyy_MM_dd)>-1){
        		logger.debug("查询孕妇血糖日期参数错误:开始日期大于结束日期");
            	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参错误,开始日期大于结束日期");
        	}
        }
        //计算分页参数
        //bloodsugarRecord.setStartNum((bloodsugarRecord.getCurPage()-1)*bloodsugarRecord.getPageSize());
        //查询体重列表
        Map<String,Object> rspMap = newBloodSugarService.listbloodsugarForPagePC(bloodsugarRecord);
        // 针对Datatable特殊处理
        if (!StringUtils.isEmpty(jsonStr)) {
        	rspMap.put("draw", draw);
            rspMap.put("recordsTotal", rspMap.get("total"));
            rspMap.put("recordsFiltered", rspMap.get("total"));
        }
        //将查询条件返回
        //rspMap.put("param", weight);
        logger.debug("out listbloodsugarForPage----arg=="+JSON.toJSONString(rspMap));
        return rspMap;
    }
    /**
     * 查询孕妇血糖----(可用于图表)
     * @param request
     * @param jsonStr
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/listbloodsugar")
    public ResultModel<Object> listbloodsugar(HttpServletRequest request, @RequestBody String jsonStr) throws Exception {
        logger.info("in listbloodsugar----arg==" + jsonStr);
        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }
        //获取实体参数
        PtBloodsugarRecord bloodsugarRecord = (PtBloodsugarRecord) JsonToEnetityUtil.jsonToObject(requestParam, PtBloodsugarRecord.class);
        //判空
        if(StringUtils.isEmpty(bloodsugarRecord.getUserId())){
        	logger.debug("out UserId----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"患者ID不能为空");
        }
        //日期查询条件判断
        if(!StringUtils.isEmpty(bloodsugarRecord.getStartDate())){
        	if(StringUtils.isEmpty(bloodsugarRecord.getEndDate())){
        		logger.debug("查询孕妇血糖日期参数单个为空");
            	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参错误,单个日期参数无法查询");
        	}else if(!bloodsugarRecord.getStartDate().equals(bloodsugarRecord.getEndDate()) && DateTimeUtil.compareDate(bloodsugarRecord.getStartDate(),bloodsugarRecord.getEndDate(), DateTimeUtil.yyyy_MM_dd)>-1){
        		logger.debug("查询孕妇血糖日期参数错误:开始日期大于结束日期");
            	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参错误,开始日期大于结束日期");
        	}
        }
        //查询体重列表
        Map<String,Object> rspMap = newBloodSugarService.listbloodsugar(bloodsugarRecord);
        //将查询条件返回
        logger.debug("out listbloodsugar----arg=="+JSON.toJSONString(rspMap));
        return new ResultModel<Object>(rspMap);
    }
    /**
     * 通过id或者userid+testDate查询
     * @return 单个对象
     */
    @ResponseBody
    @RequestMapping("/getBloodsugar")
    public ResultModel<Object> getBloodsugar(HttpServletRequest request, @RequestBody String jsonStr) throws Exception {
        logger.info("in getgymnasticBarbellForUpdate----arg==" + jsonStr);
        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }
        //获取实体参数
        PtBloodsugarRecord bloodsugarRecord = (PtBloodsugarRecord) JsonToEnetityUtil.jsonToObject(requestParam, PtBloodsugarRecord.class);
        //判空 id为空 并且userid或testDate为空
        if(StringUtils.isEmpty(bloodsugarRecord.getId()) && (StringUtils.isEmpty(bloodsugarRecord.getUserId()) || StringUtils.isEmpty(bloodsugarRecord.getTestDate()))){
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参错误");
        }
        bloodsugarRecord.setStartDate("");
        bloodsugarRecord.setEndDate("");
        //查询体重列表
        Map<String,Object> rspMap = newBloodSugarService.getbloodsugar(bloodsugarRecord);
        logger.debug("out getgymnasticBarbellForUpdate----arg=="+JSON.toJSONString(rspMap));
        return new ResultModel<Object>(rspMap);
    }
}
